//
//  DetectionViewController.m
//  Anyair
//
//  Created by karlcool on 14-5-15.
//  Copyright (c) 2014年 Karlcool. All rights reserved.
//

#import "DetectionViewController.h"



@interface DetectionViewController ()

@end

@implementation DetectionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithType:(int)type {
    
    if ([super init]) {
        dataType = type;
        
        //加载上次的数据
        thisModel = [[DataModel alloc]init];
        thisModel.PM25 = [[NSUserDefaults standardUserDefaults]objectForKey:@"PM25"];
        thisModel.methanal = [[NSUserDefaults standardUserDefaults]objectForKey:@"methanal"];
        thisModel.co2 = [[NSUserDefaults standardUserDefaults]objectForKey:@"co2"];
        thisModel.temperature = [[NSUserDefaults standardUserDefaults]objectForKey:@"temperature"];
        thisModel.humidity = [[NSUserDefaults standardUserDefaults]objectForKey:@"humidity"];
        thisModel.PM50 = [[NSUserDefaults standardUserDefaults]objectForKey:@"PM50"];
        thisModel.PM100 = [[NSUserDefaults standardUserDefaults]objectForKey:@"PM100"];
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"temperature"]==nil) {
            thisModel.temperature = @"0";
        }
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"humidity"]==nil) {
            thisModel.humidity = @"0";
        }
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"PM25"]==nil) {
            thisModel.PM25 = @"0";
        }
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"PM50"]==nil) {
            thisModel.PM50 = @"0";
        }
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"PM100"]==nil) {
            thisModel.PM100 = @"0";
        }
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"co2"]==nil) {
            thisModel.co2 = @"0";
        }
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"methanal"]==nil) {
            thisModel.methanal = @"0.00";
        }
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    mainScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
    mainScroll.backgroundColor = AIR_GRAY;
    mainScroll.contentSize =CGSizeMake(320, 461);
    mainScroll.delegate = self;
    mainScroll.showsVerticalScrollIndicator = NO;
    refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.view.bounds.size.height,self.view.frame.size.width, self.view.bounds.size.height)];
    refreshHeaderView.delegate = self;
    refreshHeaderView.title1 = @"释放开启检测";
    refreshHeaderView.title2 = @"下拉再次检测";
    refreshHeaderView.title3 = @" ";
    [refreshHeaderView refreshLastUpdatedDate];
    
    [mainScroll addSubview:refreshHeaderView];
    [self.view addSubview:mainScroll];
    
    [self loadDataViewByType:dataType];
    [self showValue];
    
    NSString *updateType;
    if (dataType==0) {
        updateType = @"pm";
    } else if (dataType==2) {
        updateType = @"hcho";
    } else if (dataType==1) {
        updateType = @"Co2";
    }
    
    if (![BluetoothManager createManager].isConnected) {
        MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:shortHub];
        [shortHub setLabelText:@"只有连接了硬件设备才能进行检测"];
        [shortHub setMode:MBProgressHUDModeText];
        [shortHub hide:YES afterDelay:2];
        [shortHub show:YES];
    }
}


- (void)viewDidAppear:(BOOL)animated {
    //定位用户当前位置
    locationManager = [[CLLocationManager alloc]init];
    locationManager.delegate = self;
    [locationManager startUpdatingLocation];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateThisValueByNotification:) name:@"updatePlaceDiy" object:nil];
}

#pragma mark -提交采集到的数据如果没有网络就存入本地数据库等到有网后提交
- (void)viewDidDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self updateValue];
}

- (void)updateValue {
    NSLog(@"上传数据");
    //如果现在处于实时监测状态那就需要在一些情况下发送本地通知
    if (co2Switch.isOn) {
        if (thisModel.co2.integerValue>=1200&&thisModel.co2.integerValue<1500) {
            //中度缺氧
            UILocalNotification *co2Notification = [[UILocalNotification alloc] init];
            if (co2Notification) {
                co2Notification.repeatInterval = NSCalendarUnitHour;
                co2Notification.alertBody = @"此处中度缺氧，建议不要久留";
                [[UIApplication sharedApplication] scheduleLocalNotification:co2Notification];
            }
        } else if (thisModel.co2.integerValue>1500) {
            //严重缺氧
            UILocalNotification *co2Notification = [[UILocalNotification alloc] init];
            if (co2Notification) {
                co2Notification.repeatInterval = NSCalendarUnitHour;
                co2Notification.alertBody = @"此处严重缺氧，请立刻离开此地";
                [[UIApplication sharedApplication] scheduleLocalNotification:co2Notification];
            }
        }
        
        if (![BluetoothManager createManager].isConnected) {
            //连接已断开
            UILocalNotification *co2Notification = [[UILocalNotification alloc] init];
            if (co2Notification) {
                co2Notification.repeatInterval = NSCalendarUnitHour;
                co2Notification.alertBody = @"蓝牙连接已断开，CO2实时监测不可用";
                [[UIApplication sharedApplication] scheduleLocalNotification:co2Notification];
            }
        }
    }
    if ([LRUserManager createManager].isLogIn) {
        NSString *updateType;
        if (dataType==0) {
            updateType = @"pm";
        } else if (dataType==2) {
            updateType = @"hcho";
        } else if (dataType==1) {
            updateType = @"Co2";
        }
        NSString *tempAddress = @"未知地点";
        if ([LRUserManager createManager].userAddress.length!=0) {
            tempAddress = [LRUserManager createManager].userAddress;
        }
        if ([LRTools checkNetWork]) {
            
            dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_LOW ,0),^{
                NSDictionary *resposeDic;
                
                if (dataType==0) {
                    resposeDic = [[LRHttpManager createHttpManager]updatePMByPhone:[LRUserManager createManager].userPhone AndLongitude:[LRUserManager createManager].userLongitude AndLatitude:[LRUserManager createManager].userLatitude AndCelsius:thisModel.temperature AndDampness:thisModel.humidity AndAddress:tempAddress AndPlacediy:@"无自定义地址" AndPm:thisModel.PM25 AndPm2:thisModel.PM50 AndPm10:thisModel.PM100];
                } else if (dataType==1) {
                    resposeDic = [[LRHttpManager createHttpManager]updateCO2ByPhone:[LRUserManager createManager].userPhone AndLongitude:[LRUserManager createManager].userLongitude AndLatitude:[LRUserManager createManager].userLatitude AndCelsius:thisModel.temperature AndDampness:thisModel.humidity AndAddress:tempAddress AndPlacediy:@"无自定义地址" AndCO2:thisModel.co2 AndCheckType:@"0"];
                } else if (dataType==2) {
                    resposeDic = [[LRHttpManager createHttpManager]updateHCHOByPhone:[LRUserManager createManager].userPhone AndLongitude:[LRUserManager createManager].userLongitude AndLatitude:[LRUserManager createManager].userLatitude AndCelsius:thisModel.temperature AndDampness:thisModel.humidity AndAddress:tempAddress AndPlacediy:@"无自定义地址" AndHCHO:thisModel.methanal];
                }
                dispatch_async (dispatch_get_main_queue(),^{
                    if ([[resposeDic objectForKey:@"code"] integerValue]==0) {
                        NSLog(@"上传成功");
                    } else {
                        NSLog(@"上传失败");
                    }
                    
                });
            });
            
        } else {
            LRDatabaseManager *manager=[LRDatabaseManager createDatabase];
            [manager.dataQueue inDatabase:^(FMDatabase *db){
                [db open];
                
                [db executeUpdate:@"insert into UpdateTable(UpdatePhone,UpdateLongitude,UpdateLatitude,UpdateCelsius,UpdateDampness,UpdateAddress,UpdatePlacediy,UpdateCO2,UpdateHOCO,UpdatePM25,UpdatePM50,UpdatePM100,UpdateTime,UpdateType,UpdateSuccess) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[LRUserManager createManager].userPhone,[LRUserManager createManager].userLongitude,[LRUserManager createManager].userLatitude,thisModel.temperature,thisModel.humidity,tempAddress,@"无自定义地址",thisModel.co2,thisModel.methanal,thisModel.PM25,thisModel.PM50,thisModel.PM100,[LRTools getNowTime],updateType,@"0"];
                
                [db close];
            }];
        }
    }
}

#pragma mark - 手动输入地址手动提交接口

- (void)updateThisValueByNotification:(NSNotification*)noti {
    NSString *updateType;
    if (dataType==0) {
        updateType = @"pm";
    } else if (dataType==2) {
        updateType = @"hcho";
    } else if (dataType==1) {
        updateType = @"Co2";
    }
    NSString *tempAddress = @"未知地点";
    if ([LRUserManager createManager].userAddress.length!=0) {
        tempAddress = [LRUserManager createManager].userAddress;
    }
    if ([LRTools checkNetWork]) {
        
        dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_LOW ,0),^{
            NSDictionary *resposeDic;
            
            if (dataType==0) {
                resposeDic = [[LRHttpManager createHttpManager]updatePMByPhone:[LRUserManager createManager].userPhone AndLongitude:[LRUserManager createManager].userLongitude AndLatitude:[LRUserManager createManager].userLatitude AndCelsius:thisModel.temperature AndDampness:thisModel.humidity AndAddress:tempAddress AndPlacediy:noti.object AndPm:thisModel.PM25 AndPm2:thisModel.PM50 AndPm10:thisModel.PM100];
            } else if (dataType==1) {
                resposeDic = [[LRHttpManager createHttpManager]updateCO2ByPhone:[LRUserManager createManager].userPhone AndLongitude:[LRUserManager createManager].userLongitude AndLatitude:[LRUserManager createManager].userLatitude AndCelsius:thisModel.temperature AndDampness:thisModel.humidity AndAddress:tempAddress AndPlacediy:noti.object AndCO2:thisModel.co2 AndCheckType:@"0"];
            } else if (dataType==2) {
                resposeDic = [[LRHttpManager createHttpManager]updateHCHOByPhone:[LRUserManager createManager].userPhone AndLongitude:[LRUserManager createManager].userLongitude AndLatitude:[LRUserManager createManager].userLatitude AndCelsius:thisModel.temperature AndDampness:thisModel.humidity AndAddress:tempAddress AndPlacediy:noti.object AndHCHO:thisModel.methanal];
            }
            dispatch_async (dispatch_get_main_queue(),^{
                if ([[resposeDic objectForKey:@"code"] integerValue]==0) {
                    NSLog(@"上传成功");
                } else {
                    NSLog(@"上传失败");
                }
                
            });
        });
        
    } else {
        LRDatabaseManager *manager=[LRDatabaseManager createDatabase];
        [manager.dataQueue inDatabase:^(FMDatabase *db){
            [db open];
            
            [db executeUpdate:@"insert into UpdateTable(UpdatePhone,UpdateLongitude,UpdateLatitude,UpdateCelsius,UpdateDampness,UpdateAddress,UpdatePlacediy,UpdateCO2,UpdateHOCO,UpdatePM25,UpdatePM50,UpdatePM100,UpdateTime,UpdateType,UpdateSuccess) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[LRUserManager createManager].userPhone,[LRUserManager createManager].userLongitude,[LRUserManager createManager].userLatitude,thisModel.temperature,thisModel.humidity,tempAddress,noti.object,thisModel.co2,thisModel.methanal,thisModel.PM25,thisModel.PM50,thisModel.PM100,[LRTools getNowTime],updateType,@"0"];
            
            [db close];
        }];
    }

}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 根据检测类型加载对应界面

- (void)loadDataViewByType:(int)type {
    
    //状态
    stateLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 90, 30)];
    stateLabel.backgroundColor = [UIColor clearColor];
    stateLabel.textAlignment = NSTextAlignmentLeft;
    stateLabel.textColor = TEXT_GRAY;
    stateLabel.font = [UIFont systemFontOfSize:14];
    stateLabel.text = @"检测完毕";
    [mainScroll addSubview:stateLabel];
    
    //温度和湿度
    temperatureLabel = [[UILabel alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-95, 5, 90, 30)];
    temperatureLabel.backgroundColor = [UIColor clearColor];
    temperatureLabel.textAlignment = NSTextAlignmentLeft;
    temperatureLabel.textColor = TEXT_GRAY;
    temperatureLabel.font = [UIFont systemFontOfSize:14];
    temperatureLabel.text = [NSString stringWithFormat:@"温度: %@℃",thisModel.temperature];
    [mainScroll addSubview:temperatureLabel];
    
    humidityLabel = [[UILabel alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-95, 30, 90, 30)];
    humidityLabel.backgroundColor = [UIColor clearColor];
    humidityLabel.textAlignment = NSTextAlignmentLeft;
    humidityLabel.textColor = TEXT_GRAY;
    humidityLabel.font = [UIFont systemFontOfSize:14];
    humidityLabel.text = [NSString stringWithFormat:@"湿度: %@%%RH",thisModel.humidity];
    [mainScroll addSubview:humidityLabel];
    //数值盘
    MDRadialProgressView *radialView = [[MDRadialProgressView alloc] initWithFrame:CGRectMake(40, 70, 240, 240)];
	radialView.progressTotal = 144;
    radialView.progressCounter = 108;
    radialView.theme.thickness = 60;
	radialView.theme.incompletedColor = [UIColor clearColor];
	radialView.theme.completedColor = CIRCLE_GRAY;
    radialView.theme.sliceDividerHidden = YES;
	radialView.label.hidden = YES;
    radialView.transform = CGAffineTransformMakeRotation(-M_PI_2/4*6);
	[mainScroll addSubview:radialView];

    dataView = [[MDRadialProgressView alloc] initWithFrame:CGRectMake(40, 70, 240, 240)];
	dataView.progressTotal = 144;
    if (dataType==0) {
        dataView.progressCounter = thisModel.PM25.intValue + 1;
    } else if (dataType==2) {
        dataView.progressCounter = thisModel.methanal.intValue + 1;
    } else if (dataType==1) {
        dataView.progressCounter = thisModel.co2.intValue + 1;
    }
    dataView.theme.thickness = 60;
	dataView.theme.incompletedColor = [UIColor clearColor];
	dataView.theme.completedColor = CIRCLE_ORANGE;
    dataView.theme.sliceDividerHidden = YES;
	dataView.label.hidden = YES;
    dataView.transform = CGAffineTransformMakeRotation(-M_PI_2/4*6);
	[mainScroll addSubview:dataView];
    
    
    //分割线
    UIView *breakLine = [[UIView alloc]initWithFrame:CGRectMake(20, dataView.frame.origin.y+dataView.frame.size.height+10, 280, 1)];
    breakLine.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.1];
    [mainScroll addSubview:breakLine];
    
    
    
    
    //中间大数值
    centerLabel = [[UILabel alloc]initWithFrame:CGRectMake(85, dataView.frame.origin.y+135, 150, 60)];
    centerLabel.textColor = [UIColor blackColor];
    centerLabel.backgroundColor = [UIColor clearColor];
    
    centerLabel.text = @"0";
    centerLabel.font = [UIFont boldSystemFontOfSize:60];
    centerLabel.textAlignment = NSTextAlignmentCenter;
    [mainScroll addSubview:centerLabel];
    
    
    smallCenterLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, centerLabel.frame.origin.y+40, 100, 60)];
    smallCenterLabel.textColor = TEXT_GRAY;
    smallCenterLabel.backgroundColor = [UIColor clearColor];
    smallCenterLabel.font = [UIFont systemFontOfSize:20];
    smallCenterLabel.textAlignment = NSTextAlignmentCenter;
    [mainScroll addSubview:smallCenterLabel];
    if (dataType==0) {
        centerLabel.text = thisModel.PM25;
        smallCenterLabel.text = @"ug/m³";
    } else if (dataType==2) {
        centerLabel.text = thisModel.methanal;
        smallCenterLabel.text = @"ppm";
    } else if (dataType==1) {
        centerLabel.text = thisModel.co2;
        smallCenterLabel.text = @"ppm";
    }
    //pm其他数据
    if (dataType==0) {
        
        UILabel *pm2_5 = [[UILabel alloc]initWithFrame:CGRectMake(40, smallCenterLabel.frame.origin.y+95, 80, 30)];
        pm2_5.textColor = AIR_GREEN;
        pm2_5.backgroundColor = [UIColor clearColor];
        pm2_5.text = @"PM 2.5";
        pm2_5.font = [UIFont systemFontOfSize:17];
        pm2_5.textAlignment = NSTextAlignmentCenter;
        [mainScroll addSubview:pm2_5];
        
        UILabel *pm5 = [[UILabel alloc]initWithFrame:CGRectMake(120, smallCenterLabel.frame.origin.y+95, 80, 30)];
        pm5.textColor = AIR_GREEN;
        pm5.backgroundColor = [UIColor clearColor];
        pm5.text = @"PM 10";
        pm5.font = [UIFont systemFontOfSize:17];
        pm5.textAlignment = NSTextAlignmentCenter;
        [mainScroll addSubview:pm5];
        
        UILabel *pm10 = [[UILabel alloc]initWithFrame:CGRectMake(200, smallCenterLabel.frame.origin.y+95, 80, 30)];
        pm10.textColor = AIR_GREEN;
        pm10.backgroundColor = [UIColor clearColor];
        pm10.text = @">PM 10";
        pm10.font = [UIFont systemFontOfSize:17];
        pm10.textAlignment = NSTextAlignmentCenter;
        [mainScroll addSubview:pm10];
        
        pm2_5Label = [[UILabel alloc]initWithFrame:CGRectMake(40, smallCenterLabel.frame.origin.y+125, 80, 30)];
        pm2_5Label.textColor = [LRTools setColorForValue:thisModel.PM25 AndType:dataType];
        pm2_5Label.backgroundColor = [UIColor clearColor];
        pm2_5Label.text = thisModel.PM25;
        pm2_5Label.font = [UIFont boldSystemFontOfSize:25];
        pm2_5Label.textAlignment = NSTextAlignmentCenter;
        [mainScroll addSubview:pm2_5Label];
        
        pm5Label = [[UILabel alloc]initWithFrame:CGRectMake(120, smallCenterLabel.frame.origin.y+125, 80, 30)];
        pm5Label.textColor = [LRTools setColorForValue:thisModel.PM50 AndType:dataType];
        pm5Label.backgroundColor = [UIColor clearColor];
        pm5Label.text = thisModel.PM50;
        pm5Label.font = [UIFont boldSystemFontOfSize:25];
        pm5Label.textAlignment = NSTextAlignmentCenter;
        [mainScroll addSubview:pm5Label];
        
        pm10Label = [[UILabel alloc]initWithFrame:CGRectMake(200, smallCenterLabel.frame.origin.y+125, 80, 30)];
        pm10Label.textColor = [LRTools setColorForValue:thisModel.PM100 AndType:dataType];
        pm10Label.backgroundColor = [UIColor clearColor];
        pm10Label.text = thisModel.PM100;
        pm10Label.font = [UIFont boldSystemFontOfSize:25];
        pm10Label.textAlignment = NSTextAlignmentCenter;
        [mainScroll addSubview:pm10Label];

    } else if (dataType==1) {
        UILabel *switchLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 30, 80, 25)];
        switchLabel.text = @"实时检测:";
        switchLabel.textColor = TEXT_GRAY;
        switchLabel.textAlignment = 0;
        switchLabel.backgroundColor = [UIColor clearColor];
        switchLabel.font = [UIFont systemFontOfSize:14];
        [mainScroll addSubview:switchLabel];
        co2Switch = [[SevenSwitch alloc]initWithFrame:CGRectMake(70, 32, 50, 25)];
        co2Switch.onColor = AIR_GREEN;
        [mainScroll addSubview:co2Switch];
        [co2Switch addTarget:self action:@selector(changeSwitchMark:) forControlEvents:UIControlEventTouchUpInside];
    }
    UILabel *noticeTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, breakLine.frame.origin.y, 100, 35)];
    noticeTitleLabel.backgroundColor = [UIColor clearColor];
    noticeTitleLabel.font = [UIFont systemFontOfSize:15];
    noticeTitleLabel.textColor = TEXT_GRAY;
    noticeTitleLabel.text = @"健康提示:";
    noticeTitleLabel.textAlignment = NSTextAlignmentLeft;
    [mainScroll addSubview:noticeTitleLabel];
    
    noticeLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(20, noticeTitleLabel.frame.origin.y+20, 270, 35)];
    noticeLabel1.backgroundColor = [UIColor clearColor];
    noticeLabel1.font = [UIFont systemFontOfSize:15];
    noticeLabel1.textColor = TEXT_GRAY;
    noticeLabel1.text = @"PM2.5含量较高";
    noticeLabel1.textAlignment = NSTextAlignmentLeft;
    [mainScroll addSubview:noticeLabel1];
    
    noticeLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(20, noticeLabel1.frame.origin.y+20, 270, 35)];
    noticeLabel2.backgroundColor = [UIColor clearColor];
    noticeLabel2.font = [UIFont systemFontOfSize:15];
    noticeLabel2.textColor = TEXT_GRAY;
    noticeLabel2.text = @"建议购买";
    noticeLabel2.textAlignment = NSTextAlignmentLeft;
    [mainScroll addSubview:noticeLabel2];
}

#pragma mark - 加载数据

- (void)showValue {
    
    if (dataType==0) {
        centerLabel.text = thisModel.PM25;
        centerLabel.textColor = [LRTools setColorForValue:thisModel.PM25 AndType:dataType];
        dataView.progressCounter = [LRTools setValueForValue:thisModel.PM25 AndType:dataType];
    } else if (dataType==2) {
        centerLabel.text = thisModel.methanal;
        centerLabel.textColor = [LRTools setColorForValue:thisModel.methanal AndType:dataType];
        dataView.progressCounter = [LRTools setValueForValue:thisModel.methanal AndType:dataType];
    } else if (dataType==1) {
        centerLabel.text = thisModel.co2;
        centerLabel.textColor = [LRTools setColorForValue:thisModel.co2 AndType:dataType];
        dataView.progressCounter = [LRTools setValueForValue:thisModel.co2 AndType:dataType];
    }
    
    if (dataView.progressCounter==1) {
        dataView.theme.completedColor = CIRCLE_GRAY;
    } else {
        dataView.theme.completedColor = CIRCLE_ORANGE;
    }
}

#pragma mark - 仪表盘重新加载新数据
- (void)reloadValueByModel:(DataModel*)model {
    centerLabel.text = @"0";
    dataView.progressCounter = 1;
    if (dataType==0) {
        [[NSUserDefaults standardUserDefaults]setObject:thisModel.PM25 forKey:@"PM25"];
        [[NSUserDefaults standardUserDefaults]setObject:thisModel.PM50 forKey:@"PM50"];
        [[NSUserDefaults standardUserDefaults]setObject:thisModel.PM100 forKey:@"PM100"];
        pm2_5Label.text = thisModel.PM25;
        pm2_5Label.textColor = [LRTools setColorForValue:thisModel.PM25 AndType:dataType];
        pm5Label.text = thisModel.PM50;
        pm5Label.textColor = [LRTools setColorForValue:thisModel.PM50 AndType:dataType];
        pm10Label.text = thisModel.PM100;
        pm10Label.textColor = [LRTools setColorForValue:thisModel.PM100 AndType:dataType];
    } else if (dataType==1) {
        [[NSUserDefaults standardUserDefaults]setObject:thisModel.co2 forKey:@"co2"];
    } else if (dataType==2) {
        [[NSUserDefaults standardUserDefaults]setObject:thisModel.methanal forKey:@"methanal"];
    }
    [[NSUserDefaults standardUserDefaults]setObject:thisModel.humidity forKey:@"humidity"];
    [[NSUserDefaults standardUserDefaults]setObject:thisModel.temperature forKey:@"temperature"];
    temperatureLabel.text = [NSString stringWithFormat:@"温度: %@℃",thisModel.temperature];
    humidityLabel.text = [NSString stringWithFormat:@"湿度: %@%%RH",thisModel.humidity];
    
    [self showValue];
}

#pragma mark - 定位回调,用以获取用户当前位置来上传
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *currentCL =  [locations lastObject];
    [LRUserManager createManager].userLongitude = [NSString stringWithFormat:@"%f",currentCL.coordinate.longitude];
    [LRUserManager createManager].userLatitude = [NSString stringWithFormat:@"%f",currentCL.coordinate.latitude];
    [manager stopUpdatingLocation];
    locationManager = nil;
     CLLocationCoordinate2D pt = (CLLocationCoordinate2D){currentCL.coordinate.latitude, currentCL.coordinate.longitude};
    searchPlace = [[BMKSearch alloc]init];
    searchPlace.delegate = self;
    [searchPlace reverseGeocode:pt];

}

#pragma mark - 定位成功后通过bmksearch反解码成当前地理位置，反解码完成后将调用此方法
- (void)onGetAddrResult:(BMKSearch*)searcher result:(BMKAddrInfo*)result errorCode:(int)error {
	if (error == 0) {
        [LRUserManager createManager].userAddress = result.strAddr;
        NSLog(@"用户当前位置:%@",result.strAddr);
	}
    searchPlace.delegate = nil;
    searchPlace = nil;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	if (refreshHeaderView) {
        [refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }

}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	if (refreshHeaderView) {
        [refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }

}

#pragma mark - EGORefreshTableDelegate
- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos {
    if ([BluetoothManager createManager].isConnected&&[BluetoothManager createManager].senor.manager.state==CBCentralManagerStatePoweredOn) {
        stateLabel.text = @"检测中...";
        DataModel *tempModel = thisModel;
        thisModel = nil;
        thisModel = [[DataModel alloc]init];
        thisModel.temperature = tempModel.temperature;
        thisModel.humidity = tempModel.humidity;
        tempModel = nil;
        [refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:mainScroll];
        
        //向硬件发送特定指令以获取数据
        [[BluetoothManager createManager]setDelegate:self];

        if (dataType==0) {
            [[BluetoothManager createManager]getPMData];
        } else if (dataType==2) {
            //甲醛
            [[BluetoothManager createManager]getMethanalData];
            
        } else if (dataType==1) {
            //二氧化碳
            [[BluetoothManager createManager]getCO2Data];
        }
    } else {
        MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:shortHub];
        [shortHub setLabelText:@"只有连接了硬件设备才能进行检测"];
        [shortHub setMode:MBProgressHUDModeText];
        [shortHub hide:YES afterDelay:2];
        [shortHub show:YES];
        [self performSelector:@selector(finishReloadingData) withObject:nil afterDelay:0.5];
    }
    
    
}
- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView*)view {

    return NO;
}

- (void)finishReloadingData{
	
	if (refreshHeaderView) {
        [refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:mainScroll];
    }

}

#pragma mark - 硬件回调方法

- (void)dataDidUpdate:(NSString*)data WhichType:(int)type {
    
    NSArray *tempArray;
    if (type==100) {
        MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:shortHub];
        [shortHub setLabelText:@"硬件已失去连接"];
        [shortHub setMode:MBProgressHUDModeText];
        [shortHub hide:YES afterDelay:2];
        [shortHub show:YES];
        [self performSelector:@selector(finishReloadingData) withObject:nil afterDelay:0.5];
        return;
    }
    if ([data isEqualToString:@"false"]) {
        
        MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:shortHub];
        [shortHub setLabelText:@"请稍后再试"];
        [shortHub setMode:MBProgressHUDModeText];
        [shortHub hide:YES afterDelay:2];
        [shortHub show:YES];
        [self performSelector:@selector(finishReloadingData) withObject:nil afterDelay:0.5];
        return;
    }
    
    
    if (type==0) {
        tempArray = [data componentsSeparatedByString:@","];
    }
    
    switch (type) {
        case 0:
            //PM
            if (tempArray.count==3) {
                thisModel.PM25 = tempArray[0];
                thisModel.PM50 = tempArray[1];
                thisModel.PM100 = tempArray[2];
            }
            break;
            
        case 2:
            //甲醛
            thisModel.methanal = data;
            break;
            
        case 1:
            //CO2
            thisModel.co2 = data;
            break;
            
        case 3:
            //温度,硬件数据是华氏温度要转化成摄氏温度
            thisModel.temperature = [LRTools turntemperature:data];
            break;
            
        case 4:
            //湿度
            thisModel.humidity = data;
            break;
            
        case 5:
            //电量
            break;
            
        default:
            break;
    }
    if (type!=0) {
        if (checkFlag==1&&type==4) {
            [[BluetoothManager createManager]getTemperatureData];
            [self performSelector:@selector(refreshFinished) withObject:nil afterDelay:2.5];
        }
        
        if (checkFlag==0&&type!=4) {
            [[BluetoothManager createManager]getHumidityData];
            checkFlag++;
        }
    } else {
        [self performSelector:@selector(refreshFinished) withObject:nil afterDelay:1.5];
    }
    
}

- (void)refreshFinished {
    stateLabel.text = @"检测完毕";
    [refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:mainScroll];
    [self reloadValueByModel:thisModel];
    checkFlag = 0;
}

#pragma mark - 开关控件代理

-(void)changeSwitchMark:(SevenSwitch*)sender {
    NSLog(@"%@实时检测",sender.on?@"打开":@"关闭");
    
    if (sender.on) {
        if ([BluetoothManager createManager].isConnected) {
            [[BluetoothManager createManager]getKeepCO2Data];
            [BluetoothManager createManager].delegate = self;
            //播放音频,用来实现长时间后台
            AVAudioSession *session = [AVAudioSession sharedInstance];
            [session setActive:YES error:nil];
            [session setCategory:AVAudioSessionCategoryPlayback error:nil];
            [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
            NSString *pathUrl = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"];
            NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:pathUrl];
            audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:NULL];
            audioPlayer.delegate = self;
            audioPlayer.volume = 0;
            audioPlayer.numberOfLoops = -1;
            [audioPlayer prepareToPlay];
            [audioPlayer play];
            co2Timer = [NSTimer scheduledTimerWithTimeInterval:11 target:self selector:@selector(updateValue) userInfo:nil repeats:YES];
        } else {
            MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
            [self.view addSubview:shortHub];
            [shortHub setLabelText:@"只有连接了硬件设备才能进行检测"];
            [shortHub setMode:MBProgressHUDModeText];
            [shortHub hide:YES afterDelay:2];
            [shortHub show:YES];
            [sender setOn:NO animated:YES];
        }
        
        
    } else {
        [co2Timer invalidate];
        co2Timer = nil;
        [[BluetoothManager createManager]closeKeepCO2];
    }
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [audioPlayer play];
}

@end
